public class Solution482 {
    public String licenseKeyFormatting(String s, int k) {
        s=s.toUpperCase();
        StringBuilder stringBuilder=new StringBuilder();
        int i=s.length()-1;
        while (i>=0&&s.charAt(i)=='-') i--;
        for (;i>=0;){
            for (int j=0;j<k;j++){
                stringBuilder.append(s.charAt(i));
                i--;
                while (i>=0&&s.charAt(i)=='-') i--;
                if (i<0){
                    return stringBuilder.reverse().toString();
                }
            }
            if (i>=0){
                stringBuilder.append('-');
            }
        }
        return stringBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution482().licenseKeyFormatting("--a-a-a-a--" ,2));
    }
}
